//
//  TuShangShowViewController.m
//  cityCar
//
//  Created by 常宽 on 14/11/4.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "TuShangShowViewController.h"
#import "PhotoStackView.h"

@interface TuShangShowViewController ()<PhotoStackViewDataSource, PhotoStackViewDelegate>
@property (nonatomic, retain)PhotoStackView *photoStack;
@property (nonatomic, retain)NSMutableArray *photos;
@property (nonatomic, retain)NSMutableArray *titleArray;
@property (nonatomic, retain)UILabel *pageLabel;
@property (nonatomic, retain)UITextView *descLabel;
@end

@implementation TuShangShowViewController

- (void)dealloc
{
    [_photoStack release];
    [_photos release];
    [_titleArray release];
    [_pageLabel release];
    [_descLabel release];
    [_urlStr release];
    [_pageCount release];
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        self.urlStr = [NSString string];
        self.photos = [NSMutableArray array];
        self.pageCount = [NSString string];
        self.titleArray = [NSMutableArray array];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    UIImageView *bom = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"照片背景.jpg"]];
    bom.frame = self.view.bounds;
    [self.view addSubview:bom];
    [self.view sendSubviewToBack:bom];
    [bom release];

//    NSLog(@"tushangURL:%@", _urlStr);
    // http://mrobot.pcauto.com.cn/v2/photo/albums?modelId=10206
    // Do any additional setup after loading the view.
    [self netWork];
    [self topSubView];
    [self setupSubviews];
}

- (void)netWork
{
    LoadingView *load= [[LoadingView alloc]initWithFrame:CGRectMake(0, 30, self.view.frame.size.width, self.view.frame.size.height - 64)];
    [self.view addSubview:load];
    [self.view bringSubviewToFront:load];
    [load release];
    
    [Connection networkHandlerWith:self.urlStr block:^(id result) {
        NSArray *array = [result objectForKey:@"photos"];
        
//        // 如果在这里给pageCount赋值,刚进界面的时候pageCount没值
//        self.pageCount = [result objectForKey:@"total"];
        
        for (NSDictionary *dic in array) {
            // 获得图片数组
            UIImage *image = [UIImage sd_imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[dic objectForKey:@"thumb"]]]];
            if (image != nil) {
                [self.photos addObject:image];
            } else {
                UIAlertView *back = [[UIAlertView alloc] initWithTitle:@"网络不给力" message:@"看不了此页，逛逛别的吧" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
                back.tag = 74912;
                [back show];
                [back release];
                break;
            }
            
            // 获得标题数组
            NSString *titleStr = [dic objectForKey:@"desc"];
            if (![titleStr isEqualToString:@""]) {
                [self.titleArray addObject:titleStr];
            } else {
                [self.titleArray addObject:[dic objectForKey:@"name"]];
            }
            
            }
//        NSLog(@"selftitleArray:%@", self.titleArray);
        [self.photoStack reloadData];
        [load removeFromSuperview];
    }];
}

// 没网返回上一页
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 74912 && buttonIndex == 0) {
        NSLog(@"返回上一页");
        [self.navigationController setNavigationBarHidden:NO animated:YES];
        self.tabBarController.tabBar.hidden = NO;
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}


- (void)topSubView
{
    UIView *topView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 64)];
//    topView.backgroundColor = [WebColor ghostWhite];
    [self.view addSubview:topView];
    [topView release];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    //    [button setBackgroundColor:[UIColor cyanColor]];
    button.titleLabel.font = [UIFont boldSystemFontOfSize:20];
    [button setTitle:@"返回" forState:UIControlStateNormal];
    [button setTitleColor:[WebColor ghostWhite] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(balck:) forControlEvents:UIControlEventTouchUpInside];
    button.frame = CGRectMake(10, 20, 40, 40);
    [topView addSubview:button];
    
    //下载按钮
    UIButton *download = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [download setBackgroundColor:[UIColor clearColor]];
    download.titleLabel.font = [UIFont boldSystemFontOfSize:20];
    [download setTitle:@"下载" forState:UIControlStateNormal];
    [download setTitleColor:[WebColor ghostWhite] forState:UIControlStateNormal];
    [download addTarget:self action:@selector(downloadAction:) forControlEvents:UIControlEventTouchUpInside];
    download.frame = CGRectMake(self.view.frame.size.width - 60, 20, 40, 40);
    [topView addSubview:download];
}
- (void)balck:(UIButton *)button
{
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    self.tabBarController.tabBar.hidden = NO;
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)setupSubviews
{
    self.photoStack = [[PhotoStackView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.width)];
    self.photoStack.center = CGPointMake(self.view.center.x, self.view.center.y - 70);
    self.photoStack.delegate = self;
    self.photoStack.dataSource = self;
    [self.view addSubview:self.photoStack];
    [self.photoStack release];
    
    
    self.pageLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 60, 30)];
    self.pageLabel.center = CGPointMake(self.view.center.x, self.view.center.y - 80 + (self.view.center.x));
    self.pageLabel.font = [UIFont boldSystemFontOfSize:17];
    self.pageLabel.textColor = [UIColor whiteColor];
    self.pageLabel.text = [NSString stringWithFormat:@"1/%@", self.pageCount];
    self.pageLabel.backgroundColor = [UIColor lightGrayColor];
    self.pageLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.pageLabel];
    [self.pageLabel release];
    
    self.descLabel = [[UITextView alloc]initWithFrame:CGRectMake(10, self.view.frame.size.height - 186, self.view.frame.size.width - 20, 100)];
    self.descLabel.textColor = [UIColor blackColor];
    self.descLabel.alpha = 0.8;
//    self.descLabel.highlighted = YES;
    self.descLabel.backgroundColor = [UIColor whiteColor];
    self.descLabel.textAlignment = NSTextAlignmentNatural;
//    self.descLabel.numberOfLines = 0;// 可以显示无限行
    self.descLabel.font = [UIFont boldSystemFontOfSize:15.f];
    self.descLabel.showsVerticalScrollIndicator = NO;
    self.descLabel.editable = NO;
    [self.descLabel sizeToFit];
    [self.view addSubview:self.descLabel];
    [self.descLabel release];
    
    

}
// 下载方法
- (void)downloadAction:(UIButton *)button
{
    // 下载图片到相册
    UIImageWriteToSavedPhotosAlbum([self.photos objectAtIndex:self.photoStack.indexOfTopPhoto], nil, nil,nil);
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"存储照片成功" message:@"您已将照片存储于图片库中，打开照片程序即可查看。" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
    [alert release];
}

#pragma mark 协议
- (NSUInteger)numberOfPhotosInPhotoStackView:(PhotoStackView *)photoStack
{
    // 显示标题并自适应
    self.descLabel.text = [self.titleArray firstObject];
    CGRect rect = [self.descLabel.text boundingRectWithSize:CGSizeMake(self.view.frame.size.width - 20, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:15.f]} context:nil];
    self.descLabel.frame = CGRectMake(10, self.view.frame.size.height - 186, self.view.frame.size.width - 20, rect.size.height + 7);
    if (rect.size.height > 140) {
        self.descLabel.scrollEnabled = YES;
        self.descLabel.frame = CGRectMake(10, self.view.frame.size.height - 186, self.view.frame.size.width - 20, 150);
    } else {
        self.descLabel.scrollEnabled = NO;
        self.descLabel.frame = CGRectMake(10, self.view.frame.size.height - 186, self.view.frame.size.width - 20, rect.size.height + 20);
    }
    
    return [self.photos count];
}
- (UIImage *)photoStackView:(PhotoStackView *)photoStack photoForIndex:(NSUInteger)index
{
    return [self.photos objectAtIndex:index];
}

#pragma mark -
#pragma mark Deck Delegate Protocol Methods

-(void)photoStackView:(PhotoStackView *)photoStackView willStartMovingPhotoAtIndex:(NSUInteger)index {
    // User started moving a photo
}

-(void)photoStackView:(PhotoStackView *)photoStackView willFlickAwayPhotoAtIndex:(NSUInteger)index {
    // User flicked the photo away, revealing the next one in the stack
}

-(void)photoStackView:(PhotoStackView *)photoStackView didRevealPhotoAtIndex:(NSUInteger)index {
    // 显示当前图片页数
    self.pageLabel.text = [NSString stringWithFormat:@"%d/%@", index + 1, self.pageCount];
    // 显示标题并自适应
    self.descLabel.text = [self.titleArray objectAtIndex:index];
    CGRect rect = [self.descLabel.text boundingRectWithSize:CGSizeMake(self.view.frame.size.width - 20, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:15.f]} context:nil];
    if (rect.size.height > 130) {
        self.descLabel.scrollEnabled = YES;
        self.descLabel.frame = CGRectMake(10, self.view.frame.size.height - 186, self.view.frame.size.width - 20, 150);
    } else {
        self.descLabel.scrollEnabled = NO;
        self.descLabel.frame = CGRectMake(10, self.view.frame.size.height - 186, self.view.frame.size.width - 20, rect.size.height + 20);
    }
}

-(void)photoStackView:(PhotoStackView *)photoStackView didSelectPhotoAtIndex:(NSUInteger)index {
    NSLog(@"selected %d", index);
    
}

- (void)viewDidUnload {
    [super viewDidUnload];
}










- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
